package com.spring.security.controller;

import com.spring.security.entity.Users;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.access.prepost.PostAuthorize;
import org.springframework.security.access.prepost.PostFilter;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/test")
public class TestController {

  @GetMapping("hello")
  public String hello() {
    return "hello security";
  }

  @GetMapping("index")
  public String index() {
    return "hello index";
  }

  /**
   * @Secured 用户具有某个角色，可以访问方法 @PreAuthoriz 注解适合进入方法前的权限校验，可以将登录用户的roles/permissions参数传到方法中
   *
   * @return
   */
  @GetMapping("update")
  // @Secured({"ROLE_sale","ROLE_manager"})
  // @PreAuthorize("hasAnyAuthority('admins')")
  @PostAuthorize("hasAnyAuthority('admins')")
  public String update() {
    System.out.println("update......");
    return "hello update";
  }

  /**
   * @PostAuthorize 注解使用并不多，在方法执行后再进行权限验证，适合验证带有返回值的权限 @PostFilter 方法返回的数据进行过滤 @PretFilter
   * 传入方法数据进行过滤
   *
   * @return
   */
  @GetMapping("getAll")
  @PostAuthorize("hasAnyAuthority('admins')")
  @PostFilter("filterObject.username == 'admin1'")
  public List<Users> getAllUser() {
    ArrayList<Users> list = new ArrayList<>();
    list.add(new Users(11, "admin1", "6666"));
    list.add(new Users(21, "admin2", "888"));
    System.out.println(list);
    return list;
  }
}
